
<template>
  <div class="container">
    <blank
      :value="showEmpty"
      :title="empty.title"
      :message="empty.message"
      :icon="empty.icon"
    />
    <van-loading
      size="24px"
      vertical
      v-if="authenting"
    >正在授权...</van-loading>
  </div>
</template>
<script>
import Security from '@/common/security'

import { getFingerprintID, detecteDevice } from '@/common/systeminfo'
import { Loading } from 'vant'
import store from '@/../store'
import qs from 'qs'
import Blank from '@/components/abnor/blank'
export default {
  components: {
    Blank,
    [Loading.name]: Loading
  },
  data () {
    return {
      showEmpty: false,
      authenting: true,
      empty: {
        title: '微信授权失败',
        message: '抱歉，当前微信授权失败...',
        icon: '/static/icons/blank_authent.png'
      },
      install: 0,
      connectId: 0,
      code: '',
      state: 'STATE',
      token: null
    }
  },
  beforeRouteEnter (to, from, next) {
    next(false)
    // 校验访问是否是微信访问
    if (detecteDevice('wechat')) {
      console.log('wechat 访问')
      let wxUserInfo = store.state.authorize.connect
      let query = qs.parse(to.query)
      console.log('no wxuserinfo', !wxUserInfo)
      console.log('no query', !query)
      console.log('query', query)
      console.log('no query code', !query.code)
      console.log('query code', query.code)
      if (!wxUserInfo && (!query || !query.code)) {
        // 未进行微信授权
        console.log('未进行微信授权 访问')
        // 1、保存当前路由地址，授权后还会跳到此地址
        sessionStorage.setItem('wxRedirectUrl', to.fullPath)

        console.log(to.fullPath)
        console.log(to.path)

        // 2、拼接微信授权地址
        // 请求微信授权,并跳转到 /authorize/wechat 路由
        let redirectUri = window.location.origin + to.path
        let params = qs.stringify({
          appid: process.env.WECHAT_APP_ID,
          redirect_uri: redirectUri,
          response_type: 'code',
          scope: 'snsapi_userinfo',
          state: 'STATE'
        })
        console.log('[params]', params)
        let redirectUrl =
          process.env.WECHAT_OAUTH_URL + '?' + params + '#wechat_redirect'
        console.log('[location.href]', redirectUrl)
        window.location.href = redirectUrl
      } else {
        console.log('微信授权 访问')
        console.log('微信授权 访问')
        next(vm => vm.setWechatAuthParams(wxUserInfo, query))
      }
    } else {
      next()
    }
  },
  created () {},
  mounted () {
    this.onAuthent()
  },
  watch: {
    token: {
      handler (v, o) {
        if (v) {
          this.$storage.setAccessToken(v)
          // this.goBack()
        }
      },
      deep: true
    }
  },
  methods: {
    setWechatAuthParams (connect, c) {
      if (connect && connect.id) {
        this.connectId = connect.id
      }
      if (c) {
        this.code = c.code
        this.state = c.state
      }
      console.log(connect, c)
    },
    async onAuthent () {
      let systemInfo = this.$storage.get('systemInfo')
      if (!systemInfo) {
        systemInfo = await getFingerprintID()
        this.$storage.set('systemInfo', systemInfo)
      }
      let authData = Security.generateSignature({
        sn: systemInfo.sn,
        os: systemInfo.os.name,
        install: this.install,
        model: systemInfo.device ? systemInfo.device.model : ''
      })
      let wxUserInfo = store.state.authorize.connect

      console.log(wxUserInfo)
      console.log(this.connectId)
      console.log(this.code)
      console.log(this.state)
      console.log(qs.parse(this.$route.query))
      console.log(qs.parse(this.$route.query))
      // qs.parse(this.$route.query),
      let params = Object.assign(
        {},
        {
          data: authData,
          spread: store.state.authorize.spread,
          connect: store.state.authorize.connect
        },
        qs.parse(this.$route.query)
      )
      console.log(params)

      this.$store
        .dispatch('authorize/wechat', params)
        .then(res => {
          console.log(res)
          this.goBack()
        })
        .catch(e => {
          console.log(e)
          this.authenting = false
          this.showEmpty = true
        })
    },
    goBack () {
      let redirectUrl = sessionStorage.getItem('authentRedirectUrl') || '/'
      console.log('[redirectUrl]', redirectUrl)
      sessionStorage.removeItem('authentRedirectUrl')
      if (this.$router.mode === 'history') {
        // this.$router.replace(redirectUrl)
        // this.$router.go(-1)
        const url = window.location.origin + redirectUrl
        window.location.href = url
      } else {
        const url = window.location.origin + '/#' + redirectUrl
        window.location.href = url
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.van-loading {
  height: 50vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
